import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('user_token') || '')
  const userInfo = ref(null)
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const nickname = computed(() => userInfo.value?.nickname || '')
  
  // 方法
  function setToken(newToken) {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('user_token', newToken)
    } else {
      localStorage.removeItem('user_token')
    }
  }

  function setUserInfo(info) {
    if (!info) {
      userInfo.value = null
      localStorage.removeItem('user_info')
      return
    }

    // 只保存必要的用户信息
    const essentialInfo = {
      id: info.id,
      username: info.username,
      nickname: info.nickname,
      avatar_data: info.avatar_data
    }
    
    userInfo.value = essentialInfo
    localStorage.setItem('user_info', JSON.stringify(essentialInfo))
  }

  function updateUserInfo(info) {
    if (userInfo.value) {
      userInfo.value = {
        ...userInfo.value,
        ...info
      }
      localStorage.setItem('user_info', JSON.stringify(userInfo.value))
    }
  }

  function clearUserInfo() {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('user_token')
    localStorage.removeItem('user_info')
  }

  // 初始化函数
  function initFromStorage() {
    const storedToken = localStorage.getItem('user_token')
    const storedInfo = localStorage.getItem('user_info')
    
    if (storedToken) {
      token.value = storedToken
    }
    
    if (storedInfo) {
      try {
        userInfo.value = JSON.parse(storedInfo)
      } catch (e) {
        console.error('Failed to parse stored user info:', e)
      }
    }
  }

  // 初始化
  initFromStorage()

  return {
    // 状态
    token,
    userInfo,
    // 计算属性
    isLoggedIn,
    nickname,
    // 方法
    setToken,
    setUserInfo,
    updateUserInfo,
    clearUserInfo
  }
}) 